import { Http, Response, Headers, RequestOptionsArgs, RequestMethod, RequestOptions } from '@angular/http';
import { Injectable } from '@angular/core';
import { UrlConstant } from '../../commons/url';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import { Observable, TimeoutError } from "rxjs";
import { NavtiveServeProvider } from '../navtiveServe/navtiveServe';


/*
  Generated class for the HttpserveProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class HttpserveProvider {

  constructor(
    public http: Http,
    private urls: UrlConstant,
    private navtive: NavtiveServeProvider,
  ) {
    console.log('Hello HttpserveProvider Provider');
  }
  public setheader(): Headers {

    let headers = new Headers();
    headers.append("Content-Type", "application/x-www-form-urlencoded");
    return headers
  }
  public request(url: string, options: RequestOptionsArgs) {
    url = this.urls.BaseUrl + url;
    return Observable.create(observer => {
      this.navtive.showLoading('加载中');
      this.http.request(url, options).timeout(this.urls.REQUEST_TIMEOUT)
        .map(res => res.json())
        .subscribe(res => {
          this.navtive.showLoading('拼命加载中');
          observer.next(res);
        }, err => {
          this.requestFailed(url, options, err.json().error);//处理请求失败
          observer.error(err.json());
        });
    });
  }

  public get(url: string, paramMap: any = null): any {
    return this.request(url, new RequestOptions({
      method: RequestMethod.Get,
      headers: this.setheader()
    }));
  }

  public post(url: string, body: any = {}): any {
    return this.request(url, new RequestOptions({
      method: RequestMethod.Post,
      params: body,
      headers: this.setheader(),
    }))
  }
  private requestFailed(url: string, options: RequestOptionsArgs, err: any): void {
    this.navtive.hideLoading();
    if (err instanceof TimeoutError) {
      this.navtive.alert('请求超时,请稍后再试!');
      return;
    }
    if (!this.navtive.isConnecting()) {
      this.navtive.alert('请求失败，请连接网络');
      return;
    }
    let msg = '请求发生异常';
    try {
      switch (Number(err.code)) {
        case 100001:
          this.navtive.showToast(err.message, 1000);
          break;
        case 10001:
          //登录页面的错误，放在Login.ts去处理
          break;
        default:

          break;
      }
    } catch (err) {
      let status = err.status;
      if (status === 0) {
        msg = '请求失败，请求响应出错';
      } else if (status === 404) {
        msg = '请求失败，未找到请求地址';
      } else if (status === 500) {
        msg = '请求失败，服务器出错，请稍后再试';
      }
      this.navtive.alert(msg);
    }
  }
}
